using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace AddressablesTool
{
    /// <summary>
    /// 依赖分析工具，用于分析Prefab的依赖资源
    /// </summary>
    public static class DependencyAnalyzer
    {
        /// <summary>
        /// 获取Prefab的所有依赖资源
        /// </summary>
        /// <param name="prefab">要分析的Prefab</param>
        /// <returns>依赖资源列表</returns>
        public static List<Object> GetDependencies(GameObject prefab)
        {
            var dependencies = new List<Object>();

            if (prefab == null) return dependencies;

            // 获取Prefab的直接依赖
            var directDependencies = EditorUtility.CollectDependencies(new Object[] { prefab });

            // 过滤掉不需要的资源类型
            foreach (var dependency in directDependencies)
            {
                if (dependency == null) continue;

                // 过滤掉脚本、场景等不需要的资源
                if (dependency is MonoScript || dependency is SceneAsset)
                    continue;

                // 过滤掉内置/公用资源（Shader、内置材质等）
                if (IsBuiltInOrCommonResource(dependency))
                    continue;

                // 过滤掉重复的资源
                if (!dependencies.Contains(dependency))
                {
                    dependencies.Add(dependency);
                }
            }

            return dependencies;
        }

        /// <summary>
        /// 获取多个Prefab的所有依赖资源（去重）
        /// </summary>
        /// <param name="prefabs">要分析的Prefab列表</param>
        /// <returns>依赖资源列表</returns>
        public static List<Object> GetDependencies(List<GameObject> prefabs)
        {
            var allDependencies = new List<Object>();

            foreach (var prefab in prefabs)
            {
                if (prefab == null) continue;

                var dependencies = GetDependencies(prefab);

                foreach (var dependency in dependencies)
                {
                    if (!allDependencies.Contains(dependency))
                    {
                        allDependencies.Add(dependency);
                    }
                }
            }

            return allDependencies;
        }

        /// <summary>
        /// 获取依赖资源的类型统计
        /// </summary>
        /// <param name="dependencies">依赖资源列表</param>
        /// <returns>类型统计字典</returns>
        public static Dictionary<string, int> GetDependencyTypeStats(List<Object> dependencies)
        {
            var stats = new Dictionary<string, int>();

            foreach (var dependency in dependencies)
            {
                if (dependency == null) continue;

                var typeName = dependency.GetType().Name;

                if (stats.ContainsKey(typeName))
                {
                    stats[typeName]++;
                }
                else
                {
                    stats[typeName] = 1;
                }
            }

            return stats;
        }

        /// <summary>
        /// 获取资源在项目中的路径
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <returns>资源路径</returns>
        public static string GetAssetPath(Object obj)
        {
            if (obj == null) return string.Empty;

            return AssetDatabase.GetAssetPath(obj);
        }

        /// <summary>
        /// 检查资源是否已经在Addressables中
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <returns>是否已在Addressables中</returns>
        public static bool IsAssetInAddressables(Object obj)
        {
            if (obj == null) return false;

            var path = GetAssetPath(obj);
            if (string.IsNullOrEmpty(path)) return false;

            // 使用Addressables的API检查资源是否在Addressables中
            var settings = UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null) return false;

            var guid = AssetDatabase.AssetPathToGUID(path);
            var entry = settings.FindAssetEntry(guid);
            return entry != null;
        }

        /// <summary>
        /// 获取资源在Addressables中的组名
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <returns>组名，如果不在Addressables中返回空字符串</returns>
        public static string GetAssetGroupName(Object obj)
        {
            if (obj == null) return string.Empty;

            var path = GetAssetPath(obj);
            if (string.IsNullOrEmpty(path)) return string.Empty;

            // 使用Addressables的API获取组名
            var settings = UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null) return string.Empty;

            var guid = AssetDatabase.AssetPathToGUID(path);
            var entry = settings.FindAssetEntry(guid);
            return entry?.parentGroup?.Name ?? string.Empty;
        }

        /// <summary>
        /// 检查资源是否为内置或公用资源
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <returns>是否为内置/公用资源</returns>
        private static bool IsBuiltInOrCommonResource(Object obj)
        {
            if (obj == null) return false;

            var path = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(path)) return false;

            // 检查是否为内置资源（路径包含"Resources/unity_builtin_extra"或"Library/unity default resources"）
            if (path.Contains("Resources/unity_builtin_extra") ||
                path.Contains("Library/unity default resources") ||
                path == "Resources/unity_builtin_extra" ||
                path == "Library/unity default resources")
            {
                return true;
            }

            // 检查是否为Shader资源（Unity会自动打包Shader）
            if (obj is Shader)
            {
                return true;
            }

            // 检查是否为内置材质（路径为空或包含"Built-in"）
            if (obj is Material material)
            {
                // 内置材质通常没有路径或路径为内置路径
                if (string.IsNullOrEmpty(path) || path.Contains("Built-in") || path.Contains("Default-"))
                {
                    return true;
                }
            }

            // 检查是否为内置纹理（如白色纹理、黑色纹理等）
            if (obj is Texture2D texture)
            {
                // 内置纹理通常没有路径或路径为内置路径
                if (string.IsNullOrEmpty(path) || path.Contains("Built-in") || path.Contains("Default-"))
                {
                    return true;
                }
            }

            // 检查是否为Unity组件类型（不需要单独打包）
            if (IsUnityComponent(obj))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 检查对象是否为Unity组件类型
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>是否为Unity组件</returns>
        private static bool IsUnityComponent(Object obj)
        {
            if (obj == null) return false;

            // 使用Component基类检查所有Unity组件
            return obj is Component;
        }
    }
}